package com.gxc.interceptor;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author GongXincheng
 * @since 2019-10-12 20:33
 */
//@Component  无效
public class TimeInterceptor implements HandlerInterceptor {

    @Value("${spring.application.name}")
    private String applicationName;

    private static final ThreadLocal<Long> START = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("Interceptor-> into TimeInterceptor the applicationName -> " + applicationName);
        START.set(System.currentTimeMillis());

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            String className = handlerMethod.getBean().getClass().getName();
            String method = ((HandlerMethod) handler).getMethod().getName();
            System.out.println("Interceptor -> " + className + "#" + method + "() -》 执行Controller");
        }

        return true;
    }

    /**
     * 注意：如果Controller有异常！则不会执行这个方法！
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        long spendTime = System.currentTimeMillis() - START.get();
        System.out.println("Interceptor -> TimeInterceptor：耗时：" + spendTime + "ms");
        START.remove();
    }

    /**
     * 异常也会执行这个方法.
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("Interceptor -> afterCompletion 通知！");
    }
}
